package com.library.base.http;

import com.library.base.http.interceptor.AuthorizationInterceptor;
import com.library.base.http.interceptor.LogInterceptor;
import com.library.base.http.interceptor.TokenExpiredCallback;
import com.library.base.http.interceptor.TokenProvider;
import com.library.base.http.service.BaseService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.annotations.NonNull;
import okhttp3.Authenticator;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class KoHttp {

    /**
     * 默认分页每页的数据条数
     */
    public static final int DEFAULT_PAGE_SIZE = 6;

    private static HashMap<String, Object> mServiceStore;

    public static String deviceId;

    private KoHttp() {
    }

    public static void init(boolean debug, String deviceId, TokenProvider provider, TokenExpiredCallback callback) {
        KoHttp.deviceId = deviceId;
        mServiceStore = new HashMap<>(6);
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(new AuthorizationInterceptor(provider, callback));
        interceptors.add(new LogInterceptor(debug));
        RetrofitClient.init(BaseService.BASE_URL, getAuthenticator(), interceptors);
    }


    public static BaseService getBaseService() {
        return getService(BaseService.class);
    }


    /**
     * 获取clazz对应的Service实例
     *
     * @param clazz
     * @return Service实例
     */
    public static <T> T getService(@NonNull Class<? extends T> clazz) {
        String key = clazz.getCanonicalName();
        T service = (T) mServiceStore.get(key);
        if (service == null) {
            service = create(clazz);
            mServiceStore.put(key, service);
        }
        return service;
    }

    /**
     * 根据传入的Service接口，创建接口实例
     *
     * @param service
     * @return Service实例
     */
    protected static <T> T create(@NonNull Class<? extends T> service) {
        return RetrofitClient.client()
                .retrofit()
                .create(service);
    }

    protected static Authenticator getAuthenticator() {
        return new Authenticator() {
            @Override
            public Request authenticate( Route route, Response response) throws IOException {
                return null;
            }
        };
    }

}
